package com.xh.bussiness.teachbook.controller;

import com.alibaba.fastjson.JSONObject;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.teachbook.bean.dto.TeachingBookDto;
import com.xh.bussiness.teachbook.bean.dto.TeachingBookModuleTree;
import com.xh.bussiness.teachbook.bean.request.*;
import com.xh.bussiness.teachbook.model.TeachingBook;
import com.xh.bussiness.teachbook.model.TeachingBookNumber;
import com.xh.bussiness.teachbook.service.*;
import com.xh.bussiness.teachbook.util.TeachingBookUtils;
import com.xh.bussiness.thirdapi.LongwenApi;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "教案管理接口")
@RestController
@RequestMapping("/teachbook/teachingbook")
public class TeachingBookController extends BaseController {

    @Autowired
    private ITeachingBookService teachingBookService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private ITeachingBookModuleService teachingBookModuleService;
    @Autowired
    private ITeachingBookModuleDetailService detailService;
    @Autowired
    private ITeachingBookPracticeService teachingBookPracticeService;
    @Autowired
    private ITeachingBookStudentResultService teachingBookStudentResultService;
    @Autowired
    private ITeachingBookTemplateService teachingBookTemplateService;
    @Autowired
    private ITeachingBookFeedbackService teachingBookFeedbackService;
    @Autowired
    private ITeachingBookAuditRecordService teachingBookAuditRecordService;
    @Autowired
    private ITeachingBookNumberService teachingBookNumberService;
    @Autowired
    private IStudentService studentService;

    @ApiOperation(value = "教案分页查询", notes = "教案分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "教案信息", required = true, dataType = "TeachingBookRequest")
    })
    @PostMapping("/queryPage")
    @ResponseBody
    public AjaxResult queryPage(XhPage page, QueryTeachingBookRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.queryTeachingBookPage(page, request));
    }


    @ApiOperation(value = " 查询待我审批的教案", notes = " 查询待我审批的教案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "教案审核状态", required = true, dataType = "Integer")
    })
    @PostMapping("/queryToAudit")
    @ResponseBody
    public AjaxResult queryToAudit(Integer status) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.queryToAudit(status));
    }


    @ApiOperation(value = " 查询已发布的教案", notes = " 查询已发布的教案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "教案的发布状态", required = true, dataType = "Integer")
    })
    @PostMapping("/queryPublished")
    @ResponseBody
    public AjaxResult queryPublished(Integer status) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.queryPublisded(status));
    }


    @ApiOperation(value = " 根据id查询教案内容", notes = " 根据id查询教案内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教案id", required = true, dataType = "String")
    })
    @PostMapping("/queryById")
    @ResponseBody
    public AjaxResult queryById(String id) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.getTeachingBookById(id));
    }


    @ApiOperation(value = " 查看备课详情", notes = " 查看备课详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lwPaikeId", value = "龙文排课id", required = true, dataType = "Integer"),
    })
    @PostMapping("/queryTeachingBookInfoByPaikeId")
    @ResponseBody
    public AjaxResult queryTeachingBookInfoByPaikeId(String lwPaikeId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.queryTeachingBookInfoByPaikeId(lwPaikeId));
    }


    @ApiOperation(value = "教案绑定排课", notes = "教案绑定排课")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "教案绑定排课", required = true, dataType = "BindPaike2TeachingBookRequest")
    })
    @PostMapping("/bindPaike2TeachingBook")
    @Transactional
    @ResponseBody
    public AjaxResult bindPaike2TeachingBook(@RequestBody BindPaike2TeachingBookRequest request) {
        String msg = teachingBookService.bindPaike2TeachingBook(request);
        if (!StringUtils.isEmpty(msg)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, msg);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "绑定成功");
    }

    @ApiOperation(value = "新增教案", notes = "新增教案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "教案信息", required = true, dataType = "TeachingBookRequest")
    })
    @PostMapping("/add")
    @Transactional
    @ResponseBody
    public AjaxResult add(@RequestBody TeachingBookRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.addTeachingBook(bean));
    }

    @ApiOperation(value = "新增上传文件教案", notes = "新增上传文件教案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "教案信息", required = true, dataType = "TeachingBookRequest")
    })
    @PostMapping("/addTeachingBookByFile")
    @Transactional
    @ResponseBody
    public AjaxResult addTeachingBookByFile(@RequestBody TeachingBookRequest bean,HttpServletRequest request) {
        if (StringUtils.isEmpty(bean.getUploadFilePath())) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "请上传备课文件！");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.addTeachingBookByFile(bean, request));
    }


    @ApiOperation(value = "修改教案", notes = "修改教案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "教案信息", required = true, dataType = "TeachingBookRequest")
    })
    @PostMapping("/modify")
    @Transactional
    public AjaxResult modify(TeachingBookRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.modifyTeachingBook(bean));
    }


    @ApiOperation(value = "删除教案", notes = "删除教案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教案id", required = true, dataType = "String")
    })
    @PostMapping("/delete")
    @Transactional
    public AjaxResult delete(String id) {
        String msg = teachingBookService.deleteTeachingBook(id);
        return new AjaxResult(msg == null, msg);
    }


    @ApiOperation(value = "教案审核", notes = "教案审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教案id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "审核状态（0草稿，1提交，2组长审核通过，3主任审核通过，4审核驳回）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "remark", value = "审核备注", dataType = "String"),
    })
    @PostMapping("/audit")
    @Transactional
    public AjaxResult audit(String id, Integer status, String remark) {
        JSONObject currentUser = (JSONObject) CacheUtils.get("user_" + UserUtils.getCurrentUserId());
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.auditTeachingBook(id, status, remark, currentUser));
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "downloadType", value = "下载类型（1：老师版，2学生版）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "teachingBookId", value = "备课id", required = true, dataType = "String"),
    })
    @ApiOperation(value = "导出word", notes = "导出word")
    @ExcludeLoginTokenIntercept
    @RequestMapping("/downloadTeachingBook2word")
    public void downloadTeachingBook2word(Integer downloadType, String teachingBookId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        TeachingBookDto teachingBookDto = teachingBookService.getTeachingBookById(teachingBookId);

        if (teachingBookDto != null) {
            String filePath = TeachingBookUtils.exportTeachingBook(downloadType, teachingBookDto, request);
            System.out.println(filePath);
            FileUtils.downloadLocalFile(teachingBookDto.getTopic(), filePath, response);
        }
    }

    @ApiOperation(value = "获取讲义结构", notes = "获取讲义结构")
    @RequestMapping("/queryTeachingBookModule")
    public AjaxResult queryTeachingBookModule(String teachingBookId) {
        List<TeachingBookModuleTree> trees =
                teachingBookModuleService.queryTeachingBookModuleList(teachingBookId);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, trees);
    }


    @ApiOperation(value = " 保存课堂总结", notes = " 保存课堂总结")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "teachingBookId", value = "讲义id", required = true, dataType = "String")
    })
    @PostMapping("/saveTeachingBookClassSummary")
    @ResponseBody
    public AjaxResult saveTeachingBookClassSummary(String content, String teachingBookId) {
        TeachingBook teachingBook = teachingBookService.getById(teachingBookId);
        if (teachingBook == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "讲义不存在");
        }
        teachingBook.setClassSummary(content);
        teachingBookService.update(teachingBook);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBook);
    }

    @ApiOperation(value = " 查询备课内容详情", notes = " 查询备课内容详情")
    @PostMapping("/queryTeachingBookModuleDetailByParams")
    @ResponseBody
    public AjaxResult queryTeachingBookModuleDetailByParams(@RequestBody QueryTeachingBookModuleDetailRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, detailService.queryTeachingBookModuleDetailByParams(request));
    }

    @ApiOperation(value = " 查询老师备课次数", notes = " 查询老师备课次数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId", value = "教师id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "refId", value = "学生/班级di", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "contractId", value = "合同id", required = true, dataType = "Integer")
    })
    @RequestMapping("/queryTeachingBookCountByTeacherId")
    @ResponseBody
    public AjaxResult queryTeachingBookCountByTeacherId(String teacherId, Integer refId, Integer contractId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.queryTeachingBookCount(teacherId, refId, contractId));
    }

    @ApiOperation(value = "作答情况录入", notes = " 作答情况录入")
    @PostMapping("/submitTeachingBookStudentResult")
    @ResponseBody
    public AjaxResult submitTeachingBookStudentResult(@RequestBody BatchSubmitStudentResultRequest batchSubmitStudentResultRequest) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookStudentResultService.submitTeachingBookStudentResult(batchSubmitStudentResultRequest.getSubmitStudentResultRequests()));
    }

    @ApiOperation(value = "备课成绩报告", notes = " 备课成绩报告")
    @GetMapping("/queryTeachingBookStudentReport")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学生id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "teachingBookId", value = "教师id", required = true, dataType = "String"),
    })
    @ResponseBody
    public AjaxResult queryTeachingBookStudentReport(String studentId, String teachingBookId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookStudentResultService.queryTeachingBookStudentReport(studentId, teachingBookId));
    }

    @ApiOperation(value = "查看讲义模板", notes = " 查看讲义模板")
    @GetMapping("/queryTeachingBookTemplate")
    @ResponseBody
    public AjaxResult queryTeachingBookTemplate() {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookTemplateService.queryAll());
    }


    @ApiOperation("保存课后课和巡堂听课")
    @RequestMapping("/saveTeachingBookFeedback")
    @ResponseBody
    public AjaxResult saveTeachingBookFeedback(SaveTeachingBookFeedbackRequest request) {
        teachingBookFeedbackService.add(request);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @ApiOperation("查询课后课和巡堂听课")
    @GetMapping("/queryTeachingBookFeedbackByBookId")
    @ResponseBody
    public AjaxResult queryTeachingBookFeedbackByBookId(String teachingBookId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookFeedbackService.queryByTeachingBookId(teachingBookId));
    }

    @ApiOperation("查询备课审核记录")
    @GetMapping("/queryTeachingBookAuditRecord")
    @ResponseBody
    public AjaxResult queryTeachingBookAuditRecord(String teachingBookId) {
        if (StringUtils.isEmpty(teachingBookId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookAuditRecordService.queryByTeachingBookId(teachingBookId));
    }

    @ApiOperation("本节课作答情况")
    @GetMapping("/queryNowTeachingBookStudentResult")
    @ResponseBody
    public AjaxResult queryNowTeachingBookStudentResult(String teachingBookId, String studentId) {
        if (StringUtils.isEmpty(teachingBookId) || StringUtils.isEmpty(studentId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.queryNowTeachingBookStudentResult(teachingBookId, studentId));
    }

    @ApiOperation("提交本节课作答情况")
    @RequestMapping("/submitNowTeachingBookStudentResult")
    @ResponseBody
    public AjaxResult submitNowTeachingBookStudentResult(@RequestBody SubmitStudentResultRequest request) {
        teachingBookStudentResultService.submitNowTeachingBookStudentResult(request);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "提交成功");
    }

    @ApiOperation("查询老师已通过的备课数据")
    @RequestMapping("/queryAcceptTeachingBookByTeacherId")
    @ResponseBody
    public AjaxResult queryAcceptTeachingBookByTeacherId(String teacherId,String refId) {
        List<TeachingBook> teachingBooks = teachingBookService.queryAcceptTeachingBookByTeacherId(teacherId,refId);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBooks);
    }

    @ApiOperation("上节备课练习作业")
    @RequestMapping("/queryPreTeachingBookPractice")
    @ResponseBody
    public AjaxResult queryPreTeachingBookPractice(String teachingBookId, String lwStudentId) {
        if (StringUtils.isEmpty(teachingBookId) || StringUtils.isEmpty(lwStudentId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookPracticeService.queryPreTeachingBookPracticeDetail(lwStudentId, teachingBookId));
    }

    @ApiOperation("提交上节课练习作业作答情况")
    @RequestMapping("/submitPreTeachingBookPracticeStudentResult")
    @ResponseBody
    public AjaxResult submitPreTeachingBookPracticeStudentResult(@RequestBody SubmitStudentResultRequest request) {
        teachingBookStudentResultService.submitPreTeachingBookPracticeStudentResult(request);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "提交成功");
    }

    /**
     * @param uniqueKey
     * @param type       [1：变式，2,：例题，3：练习题例题]
     * @param questionId
     * @return
     */
    @ApiOperation("选题存入缓存")
    @RequestMapping("/chooseQuestionToCache")
    @ResponseBody
    public AjaxResult chooseQuestionToCache(String uniqueKey, Integer type, String questionId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.chooseQuestionToCache(uniqueKey, type, questionId));
    }

    /**
     * @param uniqueKey
     * @param type      [1：变式，2,：例题，3：练习题例题]
     * @return
     */
    @ApiOperation("根据key获取缓存试题")
    @RequestMapping("/queryTeachingBookQuestionCacheByKey")
    @ResponseBody
    public AjaxResult queryTeachingBookQuestionCacheByKey(String uniqueKey, Integer type) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teachingBookService.queryTeachingBookQuestionCacheByKey(uniqueKey, type));
    }

    @ApiOperation("删除缓存中所选试题")
    @RequestMapping("/removeTeachingBookQuestionCache")
    @ResponseBody
    public AjaxResult removeTeachingBookQuestionCache(String uniqueKey, Integer type) {
        teachingBookService.removeTeachingBookQuestionCache(uniqueKey, type);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

}
